/**
 * @description:混入对象
 */
import tableColumn from "@/components/tableColumn";
import tableApi from "@/api/basic-info-manage/table-config";
import axios from 'axios'
export const mymixin = {
  components: { tableColumn },
  data() {
    return {
      dialogTableColumnVisible: false,
      nowpage: 1,
      loading: true,
      // 输入框是否可修改true为可修改
      canInput: false,
      // 添加删除修改状态---主要通过此状态来判断调用方法
      nowChanceStau: '',
      // 操作按钮的逻辑及展示数据
      addActive: true,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      editActive: false,
      dialogFormVisible: false,
      // 表格数据
      tableData: [],
      // 表单数据
      formData: {},
      treeData: [],
      image: "",
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 总页数
      totalPages: 0,
      allPointList: [],
      rightTableData: [],
      unitTypeId: '',
      unitsList: [],
      deleteFlag: true,
      tagsList: [],
      addformData: {},
      rules: {},
      postName: "",
      pictureId: '',
      token: "",
      InImgUrl: '',
      fileList: [],
      dateActive: '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近一年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }
        ]
      },
      // 地址选择
      selectedOptions: [],
      address: "",
      // 弹出框添加修改
      titleText: null,
      currentRow: null
    }
  },
  computed: {
    headers() {
      return {
        "accessToken": sessionStorage.getItem("token"),
        "organizationNo": sessionStorage.organizationNo,
        "organizationList": sessionStorage.organizationList,
        "databaseName": sessionStorage.databaseName,
        "virtualSystemNo": sessionStorage.virtualSystemNo,
        "sysDataBaseName": "DB_TDW1_OM1"
      }
    }
  },
  created () {
    this.tableColumn && (this.allTableColumn = [...this.tableColumn])
  },
  watch: {
    nowChanceStau(newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === 'del') {
        this.delmessage()
      }
    }
  },
  mounted () {
    this.loadSaveColumn()
  },
  methods: {
    // 时间
    dateFn (i) {
      this.dateActive = i;
      if (i == 1) {
        const end = new Date().getTime();
        let start = new Date();
        start = start.getTime() - 3600 * 1000 * 24 * 7;
        this.searchlist.date = [start, end];
      } else if (i == 2) {
        const end = new Date().getTime();
        let start = new Date();
        start = start.getTime() - 3600 * 1000 * 24 * 30;
        this.searchlist.date = [start, end];
      } else if (i == 3) {
        const end = new Date().getTime();
        let start = new Date();
        start = start.getTime() - 3600 * 1000 * 24 * 90;
        this.searchlist.date = [start, end];
      }
      this.search()
    },
    dateChange () {
      this.dateActive = '';
      this.search()
    },
    dateClear () {
      this.dateActive = '';
      delete this.searchlist.date;
      this.search()
    },
    // 导出
    async downloadExcel(url, param, file) {
      this.loading = true;
      const { data: data } = await axios({
        method: "post",
        url: this.$baseurl.webServiceUrl + url,
        'responseType': "blob",
        headers: {
          'accessToken': sessionStorage.token,
          'databaseName': sessionStorage.databaseName,
          'organizationList': sessionStorage.organizationList,
          'organizationNo': sessionStorage.organizationNo,
          'virtualSystemNo': sessionStorage.virtualSystemNo
        },
        data: param.entity || param
      })
      this.loading = false;
      const link = document.createElement("a");
      link.download = file;
      link.style.display = "none";
      link.href = URL.createObjectURL(data);
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    },
    // 列配置
    showColumn () {
      this.dialogTableColumnVisible = true
    },
    saveColumn () {
      this.$refs.tableColumn && this.$refs.tableColumn.save()
    },
    cancelColumn (reload) {
      this.dialogTableColumnVisible = false
      reload && this.loadSaveColumn()
    },
    loadSaveColumn () {
      let path = this.$route.path
      // if (['/production-batch-query', '/create-production-batch'].includes(path)) {
      //   path = path + this.batchType
      // }
      tableApi.queryByUrlAndAccountAndOrganizationNo(path).then(res => {
        let fieldContentStr = res.data?.fieldContentStr;
        let fieldContent = fieldContentStr && JSON.parse(fieldContentStr);
        if (fieldContent) {
          let tableColumn = []
          fieldContent.map(el => {
            let index = this.allTableColumn.findIndex(ele => {
              return ele.prop === el.prop
            })
            el.show && tableColumn.push(this.allTableColumn[index])
          })
          this.tableColumn = tableColumn
        }
      })
    },
    // 排序
    changeTableSort(column) {
      this.sortList = column.order ? [
        { property: column.prop, direction: column.order == "ascending" ? 'asc' : 'desc' }
      ] : []
      this.getTableDataList()
    },
    // 填充表格空白行
    addblankmet() {
      let havline = this.tableData.length % this.pageSize
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({ 'indflag': i + this.tableData.length + 1, 'index': i + this.tableData.length + 1 });
          }
        }
      }
    },
    // 添加
    add() {
      this.canInput = true;
      this.nowChanceStau = 'add'
      this.formData = {}
      this.image = "";
      this.tagsList = [];
      this.unitTypeId = ''
      this.unitsList = []
      this.fileList = []
      this.basicUrl = this.reseUrl;
      this.postName = ""
      this.InImgUrl = ''
      this.titleText = "添加"
      this.dialogFormVisible = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
    },
    // 修改
    edit(data) {
      this.nowChanceStau = 'edit'
      this.basicUrl = this.reseUrl;
      this.titleText = "修改"
      this.dialogFormVisible = true;
      this.canInput = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false
      data && this.handleEdit && this.handleEdit(data)
    },
    // 删除
    del() {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          this.nowChanceStau = 'del'
          // this.resetActionBar()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          // this.resetActionBar()
          if (this.tableData.length > 0) {
            // alert(1)
            this.$refs.tableData.clearSelection();
          } else if (this.treeData.length > 0) {
            this.$refs.tree.setCheckedKeys([]);
          }
          // this.resetActionBar();
        });
      this.formData = {}
      this.postName = ""
      this.nowChanceStau = "";
      this.canInput = true;
      this.addActive = true;
      // this.delActive = false;
      this.saveActive = false;
      this.editActive = false
      this.cancelActive = false;
    },
    // 取消
    cancel(formData) {
      this.deleteFlag = true;
      this.nowChanceStau = '';
      this.fileList = []
      this.formData = {};
      this.image = "";
      this.pictureId = '';
      this.basicUrl = "";
      this.rightTableData = [];
      this.tagsList = [];
      this.selectedOptions = [];
      this.unitTypeId = ''
      this.unitsList = []
      this.postName = ""
      this.address = "";
      this.dialogFormVisible = false;
      this.addformData = {}
      this.InImgUrl = ''
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      if (formData) {
        this.$refs['formData']?.resetFields();
        this.$refs['tableData']?.setCurrentRow()
      }
    },
    // 初始化操作栏状态
    resetActionBar() {
      this.nowChanceStau = ''
      this.formData = {}
      this.rightTableData = []
      this.fileList = []
      this.image = ""
      this.pictureId = ''
      this.unitTypeId = ''
      this.unitsList = []
      this.InImgUrl = ''
      this.basicUrl = this.reseUrl;
      this.postName = ""
      this.canInput = false;
      this.dialogFormVisible = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false
    },
    search(searchlist) {
      searchlist && (this.searchlist = searchlist)
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 循环过滤树形数组
    filterTreeKey(arr) {
      let newArr = []
      newArr = arr?.map(item => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterTreeKey(
              item.child
            )
          }
        } else {
          delete item.child
        }
        return item
      })
      newArr = newArr?.filter(item => item != null)
      return newArr
    },
    // 时间戳格式化
    formatDateTime(val) {
      var time = new Date(val);
      var year = time.getFullYear(); // 取得4位数的年份
      var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
      var date = time.getDate(); // 返回日期月份中的天数（1到31）
      // var hour = time.getHours(); // 返回日期中的小时数（0到23）
      // var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
      // var second = time.getSeconds(); // 返回日期中的秒数（0到59）
      return year + "年" + month + "月" + date + "日";
      // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;
    },
    // 时间戳格式化
    formatDateTime_(val) {
      var time = new Date(val);
      var year = time.getFullYear(); // 取得4位数的年份
      var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
      month = month < 10 ? ('0' + month) : month;
      var date = time.getDate(); // 返回日期月份中的天数（1到31）
      date = date < 10 ? ('0' + date) : date;
      // var hour = time.getHours(); // 返回日期中的小时数（0到23）
      // var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
      // var second = time.getSeconds(); // 返回日期中的秒数（0到59）
      return year + "-" + month + "-" + date;
      // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;
    },
    formatDateTimeMHS(val) {
      if (val) {
        var time = new Date(val);
        var year = time.getFullYear(); // 取得4位数的年份
        var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
        month = month < 10 ? ('0' + month) : month;
        var date = time.getDate(); // 返回日期月份中的天数（1到31）
        date = date < 10 ? ('0' + date) : date;
        var hour = time.getHours(); // 返回日期中的小时数（0到23）
        hour = hour < 10 ? ('0' + hour) : hour;
        var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
        minute = minute < 10 ? ('0' + minute) : minute;
        var second = time.getSeconds(); // 返回日期中的秒数（0到59）
        second = second < 10 ? ('0' + second) : second;
        return year + "-" + month + "-" + date + ' ' + hour + ':' + minute + ':' + second;
        // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;}
      }
    },
    setOptions (config, field, option) {
      let index = config.findIndex(el => {
        return el.prop === field
      })
      index !== -1 && (config[index].options = option)
    }
  }
}
